
Ext.namespace('sys.bdzpg');

	// 主页面
	sys.bdzpg.MailViewer = Ext.extend(Ext.Panel, {
		
		/**
		 * 左侧变电站树
		 */ 
		bdztree : null,
		
		/**
		 * 右侧屏柜列表
		 */ 
		pg : null,
		
		border : false,
		
		/**
	     * 初始化
		 */
		initComponent : function() {
			
			var obj = this;
			
			this.addListener('render', function() {
				obj.startViewer.defer(1, obj);
			});

			this.layout	= 'fit';
			
			sys.bdzpg.MailViewer.superclass.initComponent.call(this);
		},
		
		/**
		 * 初始化顺序处理
		 */
		startViewer : function() {
			
			// 初始化页面
			this.renderViewer();
			// grid绑定菜单
			this.pg.menuCreate();
			// 增加拖拽事件
			this.pg.ddCreate();
		},
		
		/**
		 * 加载控件
		 */
		renderViewer : function() {

			var obj = this;

			//----------------------------------------------------------------------
			//	变电站树生成
			//----------------------------------------------------------------------
			this.bdztree = new sys.bdzpg.BdzTree({
				region				: 'west',
				layout              : 'fit',
				border              : false,
				split				: true,
				collapsible			: true,
				animCollapse		: false,
				width				: 200,    
                minSize				: 175,   
                maxSize				: 250,
                title               : '变电站列表'
               
			});
			
			//----------------------------------------------------------------------
			//	变电站树事件 
			//----------------------------------------------------------------------
			this.bdztree.on({
				
				// 单击时
				'loadPgGrid' : function (node) {
					Ext.getCmp('entityJg.bdzid').setValue(node.id);
					Ext.getCmp('bdzname').setValue(node.text);
					obj.pg.gridstore.baseParams['id'] = node.id;
					obj.pg.gridstore.reload();
				},
				'resetPg' : function (node) {
					obj.pg.detail.getForm().reset();
					Ext.getCmp('entityJg.bdzid').setValue('');
					Ext.getCmp('bdzname').setValue('');
					obj.pg.gridstore.removeAll();
				}
				
			})

			//----------------------------------------------------------------------
			//	屏柜列表生成
			//----------------------------------------------------------------------
			this.pg = new sys.bdzpg.BdzPg({
				region				: 'center',
				layout              : 'border',
                maxSize				: 250,
              	title               : '屏柜信息'
			});
			
			//----------------------------------------------------------------------
			//	屏柜事件 
			//----------------------------------------------------------------------
			this.pg.on({
				
				// 新建
				'getBdzid' : function () {

					if (obj.bdztree.tree.getSelectionModel().getSelectedNode() != null) {
						Ext.getCmp('entityJg.bdzid').setValue(obj.bdztree.tree.getSelectionModel().getSelectedNode().id) ;
						Ext.getCmp('bdzname').setValue(obj.bdztree.tree.getSelectionModel().getSelectedNode().text) ;
					} else {
						Ext.getCmp('entityJg.bdzid').setValue('0');
						Ext.getCmp('bdzname').setValue('');
					}
				}
				
			})

			var viewer = ({
				layout          : 'border',
				border			: false,
				items           : [obj.bdztree, obj.pg]
			})
			
			this.add(viewer);

			if ((typeof this.layout) == "object") this.doLayout();

		}
		
	});

	/**
	 * 左侧变电站树
	 */
	sys.bdzpg.BdzTree = Ext.extend(Ext.Panel, {
	
		/**
	     * 初始化
		 */
		initComponent : function() {
			
			var obj = this;
			
			this.tree = new Ext.tree.TreePanel({
				
	            id:"mytree",   
	            root : new Ext.tree.AsyncTreeNode({   
	        		id : "0", 
	        		draggable:false, 
	        		singleClickExpand:true, 
	        		text : treetitle,
	        		qtip:'100'
				}),   
				loader:new Ext.tree.TreeLoader({
	        		url : 'bdz!getBdzTree.do?parentid=',
	        		listeners:{"beforeload":function(loader, node){ 
							loader.url ='bdz!getBdzTree.do?parentid=' + node.id ;
	        		}}
	   		 	}),
		        useArrows:true,
		        autoScroll:true,
		        animate:true

			})
			this.tree.root.expand();
			this.tree.on({
	
				'click' : function(node){

					// 变电站的时候
					if (node.id != '0' && node.parentNode.id != '0') {
						obj.fireEvent('loadPgGrid', node)
					} else {
						obj.fireEvent('resetPg');
					}
				}
				
			})
			
			// 注册事件
			this.addEvents(
				'loadPgGrid',
				'resetPg'
			);

			this.items = [this.tree];
			
			sys.bdzpg.BdzTree.superclass.initComponent.call(this);
			
		}
		
	});
	
	/**
	 * 右侧变电站屏柜
	 */
	sys.bdzpg.BdzPg = Ext.extend(Ext.Panel, {
		
		/**
		 * 屏柜列表
		 */
		grid : null,
		
		/**
		 * 屏柜列表数据源
		 */
		gridstore : null,

		/**
		 * 屏柜详细信息
		 */
		detail : null,

		/**
	     * 初始化
		 */
		initComponent : function() {
			
			var obj = this;
			
			//----------------------------------------------------------------------
			//	列表数据源
			//----------------------------------------------------------------------
			this.gridstore = new Ext.data.Store({
				proxy :new Ext.data.HttpProxy({
					url :'bdz!getBdzJgList.do?searchBean.con1=2&searchBean.con2=PGLX'
				}),
				reader :new Ext.data.JsonReader({
					root :'result',
					totalProperty :'totalCount',
					fields : ['id', 'bdzid', 'jgbh', 'jgmc', 'dydj', 'dydjname', 'jglx', 'jglxname','tyrq']
				}),
				autoLoad:false,
				remoteSort :false
			});

			//----------------------------------------------------------------------
			//	加载列表
			//----------------------------------------------------------------------
			this.grid = new Ext.grid.GridPanel({
				id					: "bdzpg_grid",
				store 				: obj.gridstore,
				region 				: 'west',
				width				: 600,
				ddGroup				: "gridDDGroup",
				enableDragDrop		: true,
				stripeRows			: true,
				split				: true,
				collapsible			: true,
				animCollapse		: false,
				cm: new Ext.grid.ColumnModel({
	        		defaults: {
	            		sortable: true
	        		},
	        		columns: [
	        			new Ext.grid.RowNumberer(),
	            		//sm,
						{	id:'id',
							header :"序号",
							width :50,
							dataIndex :'id',
							sortable :true,
							hidden :true
						}, {
							header :"屏柜编号",
							width :70,
							dataIndex :'jgbh',
							sortable :true,
							align:'center'
						}, {
							header :"屏柜名称",
							width :70,
							dataIndex :'jgmc',
							sortable :true,
							align:'center'
						},{
							header :"电压等级",
							width :120,
							dataIndex :'dydjname',
							sortable :true,
							align:'center'
						},{
							header :"屏柜类型",
							dataIndex :'jglxname',
							sortable :true,
							align:'center'
						},{
							header :"投运日期",
							width :120,
							dataIndex :'tyrq',
							sortable :true,
							align:'center'
						}]
				}),
				selModel  : new Ext.grid.RowSelectionModel({singleSelect : true}),
				loadMask : {
					msg :'载入中,请稍候...'
				},
				viewConfig:{
					forceFit:true
				},
				tbar :[
					{
						id :'noteList_query',
						text :'刷新',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/page_find.png',
			            handler:function() {
			            	obj.gridstore.reload();
        				}
					}, btn_delete ? '' : '-',{
						id :'bdz_delete',
						text :'删除',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/delete.gif',
        				hidden:btn_delete,
        				handler:function() {
        					obj.deletePg();
        				}
					}
				],
				bbar : new Ext.PagingToolbar({
					store : obj.gridstore,
					pageSize:100,
					displayInfo :true,
					displayMsg :'共 {2} 条',
					emptyMsg :"没有数据显示！"
				}),
				listeners:{'rowdblclick':function(row) {
					obj.getDetail();
				}}
			});
			
			//----------------------------------------------------------------------
			//	加载详细信息
			//----------------------------------------------------------------------
			this.detail = new Ext.form.FormPanel({
				id : 'bdzpg_detail',
				region : 'center',
				bodyStyle  : 'padding: 10px; background-color: #DFE8F6',
				method :'POST',
				labelAlign:'right',
				tbar :[
					{
						id :'bdz_insert',
						text :'新建',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/add.gif',
			            //hidden:btn_insert,
        				handler:function() {
        					obj.detail.getForm().reset();
        					obj.fireEvent('getBdzid');
        				}
					}, btn_save ? '' : '-',{
						text:'保存',
						icon:contextpath + "/images/save2.gif",
						hidden:btn_save,
						handler: function() {
        					obj.submit();
        				}
					}, btn_save ? '' : '-',{
						text:'另存为',
						icon:contextpath + "/images/save2.gif",
						hidden:btn_save,
						handler: function() {
        					obj.submit(1);
        				}
					}
				],
		        items: [
	        	{
					xtype : 'textfield',
					fieldLabel :'变电站名称',
    				width: 150,
        			name: 'bdzname',
        			id : 'bdzname',
					allowBlank : false,
					readOnly : true
        		}, {

					xtype : 'textfield',
					fieldLabel :'屏柜编号',
    				width: 150,
        			name: 'entityJg.jgbh',
        			id : 'entityJg.jgbh',
					allowBlank : false,
					maxLength :25
        		}, {

					xtype : 'textfield',
					fieldLabel :'屏柜名称',
    				width: 150,
        			name: 'entityJg.jgmc',
        			id : 'entityJg.jgmc',
					allowBlank : false,
					maxLength :50
        		}, {
					fieldLabel :'电压等级',
					name :'dydj',
					id : 'dydj',
					xtype : 'combo',
					width:150,
					hiddenName : 'entityJg.dydj',
					store : new Ext.data.Store({
						proxy : new Ext.data.HttpProxy({
							url : 'dic!getDicJson.do?dic.itemType=DYDJ'
						}),
						reader : new Ext.data.JsonReader({}, ['itemId', 'itemName']),
						autoLoad : true,
						listeners:{'load' : function() {
								var r = new Ext.data.Record({itemId:'', itemName:''});
								Ext.getCmp('dydj').store.insert(0,r);
							
						}}
					}),
					displayField : 'itemName',
					valueField : 'itemId',
					forceSelection : true,
					selectOnFocus : true,
					editable : false,
					triggerAction : 'all',
					mode : 'local',
					allowBlank : false,
					emptyText:'请选择'
       			}, {
					fieldLabel :'屏柜类型',
					name :'jglx',
					id : 'jglx',
					xtype : 'combo',
					width:150,
					hiddenName : 'entityJg.jglx',
					store : new Ext.data.Store({
						proxy : new Ext.data.HttpProxy({
							url : 'dic!getDicJson.do?dic.itemType=PGLX'
						}),
						reader : new Ext.data.JsonReader({}, ['itemId', 'itemName']),
						autoLoad : true,
						listeners:{'load' : function() {
								var r = new Ext.data.Record({itemId:'', itemName:''});
								Ext.getCmp('jglx').store.insert(0,r);
							
						}}
					}),
					displayField : 'itemName',
					valueField : 'itemId',
					forceSelection : true,
					selectOnFocus : true,
					editable : false,
					triggerAction : 'all',
					mode : 'local',
					allowBlank : false,
					emptyText:'请选择'
        		}, {
    				xtype : 'datefield',
    				fieldLabel : '投运日期',
    				width: 100,
        			name: 'entityJg.tyrq',
        			id : 'entityJg.tyrq',
        			editable:false,
        			format:'Y-m-d'
        		},{
        			xtype: 'hidden',
        			name: 'entityJg.id',
        			id:'entityJg.id',
        			value:'0'
        		},{
        			xtype: 'hidden',
        			name: 'entityJg.bdzid',
        			id:'entityJg.bdzid',
        			value:'0'
        		},{
        			xtype: 'hidden',
        			name: 'entityJg.state',
        			id:'entityJg.state',
        			value:'2'
        		}]
			});
			
			this.detail.addEvents(
				'getBdzid'
			);

			this.items = [this.grid, this.detail];
			
			sys.bdzpg.BdzPg.superclass.initComponent.call(this);
			
		},
	
		/**
		 * 菜单绑定
		 */
		menuCreate: function (){

			var obj = this;

			var actEdit = new Ext.Action({
				id			: 'menu_edit',
				text		: '修改',
				tooltip		: '修改当前屏柜',
				iconCls		: 'icon_edit',
				handler		: function() { obj.getDetail()}
			});

			var actDelete = new Ext.Action({
				id			: 'menu_delete',
				text		: '删除',
				tooltip		: '删除当前屏柜',
				iconCls		: 'icon_delete',
				hidden      : btn_delete,
				handler		: function() { obj.deletePg()}
			});
			
			obj.commandMenu = new Ext.menu.Menu({
				minWidth	: 160,
				items	: [
					actEdit, '-',
					actDelete
				]
			});
			
			obj.grid.on('rowcontextmenu',function (grid, rowIndex, e) {
      			e.preventDefault();
      			obj.grid.getSelectionModel().selectRow(rowIndex);
        		obj.commandMenu.showAt(e.getXY());   
			});
			
		},
		
		/**
		 * 拖拽
		 */
		ddCreate: function () {
			
			var obj = this;
			
			var formPanelDropTarget = new Ext.dd.DropTarget(obj.detail.body.dom, {
				ddGroup     : 'gridDDGroup',
				notifyEnter : function(ddSource, e, data) {
					obj.detail.body.stopFx();
					obj.detail.body.highlight();
				},
				notifyDrop  : function(ddSource, e, data){
					
					var record = ddSource.dragData.selections[0]['data'];
					
					for (var p in record) {
						try {
							obj.detail.getForm().findField("entityJg." + p).setValue(record[p]);
						} catch (e) {
							
						}
					}
					
					obj.detail.getForm().findField("entityJg.dydj").setRawValue(record['dydjname']);
					obj.detail.getForm().findField("entityJg.jglx").setRawValue(record['jglxname']);
					
					obj.fireEvent('getBdzid');
					
					return(true);
				}
			});
			
		},

		/**
		 * 提交保存
		 */
		submit: function(copy) {
			
			var obj = this;
			if(copy==1){
			obj.detail.getForm().findField("entityJg.id").setValue(0);
			}
			// 验证有效性
        	if (this.detail.getForm().isValid()) {

				// 提交
				this.detail.getForm().submit({
					waitMsg :'保存中...',
					url:'bdz!saveJg.do',
					success : function(form, action) {
						
						Ext.MessageBox.alert('提示', action.result.msg, function() {
						
							if (Ext.isEmpty(action.result.rep)) {
								obj.detail.getForm().findField("entityJg.id").setValue(action.result.id);
								obj.gridstore.reload();
							}
						});
					},
					failure : function(action) {
						Ext.MessageBox.alert('提示', '保存失败。');
					}
				});
        	}
			
		},
		
		/**
		 * 删除
		 */
		deletePg: function() {
			
			var obj = this;
			
			if (!obj.grid.getSelectionModel().hasSelection()) {
				Ext.MessageBox.alert("提示","请先选择要删除的记录");
				return;
			}
			
			var ids = obj.grid.getSelectionModel().getSelected()['data']['id'];
			
			Ext.MessageBox.confirm('提示', '确定要删除选中的【' + obj.grid.getSelectionModel().getSelected()['data']['jgmc'] + '】记录吗？', function (btn) {
				
				if (btn == 'yes') {

					Ext.Ajax.request({
						method :'POST',
						url :'bdz!deleteJg.do',
						params : {
							id :ids
						},
						success : function(response) {
							
							Ext.MessageBox.alert('提示', response.responseText, function () {
								obj.grid.store.reload();
							});
						},
						failure : function() {
							Ext.MessageBox.alert('提示', '删除失败！');
						}
					});
				}

			});
			
		},
		
		/**
		 * 获得详细信息
		 */
		getDetail: function() {

			var record = this.grid.getSelectionModel().getSelected()['data'];
			
			for (var p in record) {
				
				try {
					this.detail.getForm().findField("entityJg." + p).setValue(record[p]);
				} catch (e) {
					
				}
			}

			this.detail.getForm().findField("entityJg.dydj").setRawValue(record['dydjname']);
			this.detail.getForm().findField("entityJg.jglx").setRawValue(record['jglxname']);
		}
	
	});